package com.ns.scs.rsr.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ns.basic.dict.service.IDictItemEntryService;
import com.ns.basic.dict.vo.DictItemEntryVO;
import com.ns.core.annotations.ReqLog;
import com.ns.core.bo.IdsBO;
import com.ns.core.current.config.SymbolsMark;
import com.ns.core.enums.GeneralEnum;
import com.ns.core.sentinel.LimitType;
import com.ns.core.sentinel.RateLimiter;
import com.ns.core.utils.StpUtil;
import com.ns.core.utils.sg.ResultError;
import com.ns.core.utils.sg.ResultOk;
import com.ns.scs.msg.service.IMsgService;
import com.ns.scs.rsr.bo.RsrPageBO;
import com.ns.scs.rsr.bo.RsrSettledBO;
import com.ns.scs.rsr.dto.RsrPageDto;
import com.ns.scs.rsr.entry.RsrApplyEntry;
import com.ns.scs.rsr.entry.RsrEntry;
import com.ns.scs.rsr.service.IRsrApplyService;
import com.ns.scs.rsr.service.IRsrService;
import com.ns.scs.rsr.vo.RsrInfoVO;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * 资源申请相关操作
 *
 * @author lw
 * @since 2024-11-15
 */
@RestController
@RequestMapping("/rsr/apply")
@RequiredArgsConstructor
@CrossOrigin
public class RsrApplyController {

    private final IRsrApplyService applyService;

    private final IRsrService service;

    private final IMsgService msgService;

    private final IDictItemEntryService dictItemEntryService;

    /**
     * 逻辑删
     *
     * @param id 参数
     */
    @GetMapping("delete")
    @ReqLog(module = "资源申请模块", name = "逻辑删")
    ResultOk delete(Long id) {
        return ResultOk.getByBoolean(applyService.removeById(id));
    }

    /**
     * 删 - 根据id列表
     *
     * @param bo id集合
     */
    @PostMapping("deleteByIds")
    @ReqLog(module = "资源申请模块", name = "批量删")
    public ResultOk deleteByIds(@RequestBody IdsBO bo) {
        return ResultOk.getByBoolean(applyService.removeBatchByIds(bo.getIds()));
    }

    /**
     * 查询详情
     *
     * @param id 参数
     */
    @GetMapping("getById")
    @ReqLog(module = "资源申请模块", name = "详情")
    public ResultOk get(Long id) {
        return ResultOk.getSuccessData(applyService.getApplyById(id));
    }

    /**
     * 查-集合
     *
     * @param bo 参数
     */
    @PostMapping("getList")
    @ReqLog(module = "资源申请模块", name = "查-集合")
    @RateLimiter(time = 5, count = 15, limitType = LimitType.IP)
    public ResultOk getList(@RequestBody RsrPageBO bo) {
        RsrPageDto dto = new RsrPageDto();
        BeanUtils.copyProperties(bo, dto);
        Page<RsrInfoVO> page = applyService.getList(dto);
        return ResultOk.getPageData(page.getTotal(), page.getRecords());
    }


    /**
     * 查-资源投放
     *
     * @param bo 参数
     */
    @PostMapping("getSlotRsr")
    @ReqLog(module = "资源申请模块", name = "查-资源投放-集合", authFlag = false)
    @RateLimiter(time = 5, count = 15, limitType = LimitType.IP)
    public ResultOk getSlotRsr(@RequestBody RsrPageBO bo) {
        RsrPageDto dto = new RsrPageDto();
        BeanUtils.copyProperties(bo, dto);
        dto.setAuditStatus(SymbolsMark.ONE);
        Page<RsrInfoVO> page = applyService.getList(dto);
        return ResultOk.getPageData(page.getTotal(), page.getRecords());
    }

    /**
     * 资源审核
     *
     * @param id     参数
     * @param status 状态
     */
    @GetMapping("audit")
    @ReqLog(module = "资源申请模块", name = "审核")
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public ResultOk audit(Long id, Integer status) {
        RsrApplyEntry applyEntry = applyService.getById(id);
        applyEntry.setStatus(status);
        if (!applyService.saveOrUpdate(applyEntry)) {
            throw new ResultError("资源投放申请审核失败！");
        }
        RsrEntry entry = service.getById(applyEntry.getResourceId());
        if (Objects.isNull(entry)) {
            throw new ResultError("未获取到资源信息！");
        }
        entry.setAuditStatus(status);
        service.saveOrUpdate(entry);

        // 站内信息
        String mstTemplate = "您投放的资源【%s】审核完成,审核结果：【%s】";
        List<String> params = new ArrayList<>();
        params.add(entry.getName());
        List<DictItemEntryVO> items = dictItemEntryService.listByDictCode(GeneralEnum.DICT.AUDIT_STATUS.getKey());
        for (DictItemEntryVO item : items) {
            if (StringUtils.pathEquals(item.getCode(), String.valueOf(status))) {
                params.add(item.getName());
                break;
            }
        }
        msgService.sendInnerMsg(applyEntry.getApplier(), applyEntry.getSid(), mstTemplate, params);
        return ResultOk.getSuccess();
    }

    /**
     * 资源投放
     *
     * @param bo 参数
     */
    @PostMapping("check-in")
    @ReqLog(module = "资源申请模块", name = "投放申请")
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public ResultOk checkIn(@RequestBody RsrSettledBO bo) {
        RsrEntry entry;
        RsrApplyEntry applyEntry;
        try {
            if (Objects.nonNull(bo.getId())) {
                entry = service.getById(bo.getResourceId());
                BeanUtils.copyProperties(bo, entry);
                entry.setId(bo.getResourceId());
                entry.setStatus(SymbolsMark.ZERO);
                entry.setAuditStatus(SymbolsMark.ZERO);
                if (service.saveOrUpdate(entry)) {
                    applyEntry = applyService.getById(bo.getId());
                    applyEntry.setNote(entry.getNote());
                    applyEntry.setModifier(StpUtil.getLoginUserId());
                    applyEntry.setModifyTime(new Date());
                    applyService.saveOrUpdate(applyEntry);
                }
            } else {
                Long sort = service.getMaxSort();
                entry = new RsrEntry();
                entry.setSort((Objects.nonNull(sort) ? sort : 0) + 1);
                BeanUtils.copyProperties(bo, entry);
                entry.setStatus(SymbolsMark.ZERO);
                entry.setAuditStatus(SymbolsMark.ZERO);
                if (service.saveOrUpdate(entry)) {
                    applyEntry = new RsrApplyEntry();
                    applyEntry.setResourceId(entry.getId());
                    applyEntry.setApplyTime(new Date());
                    applyEntry.setApplier(StpUtil.getLoginUserId());
                    applyEntry.setStatus(entry.getAuditStatus());
                    applyEntry.setCreator(StpUtil.getLoginUserId());
                    applyEntry.setCreateTime(new Date());
                    applyEntry.setModifier(StpUtil.getLoginUserId());
                    applyEntry.setModifyTime(new Date());
                    applyEntry.setNote(entry.getNote());
                    applyService.saveOrUpdate(applyEntry);
                }
            }
        } catch (Exception e) {
            throw new ResultError("资源投放失败！");
        }
        return ResultOk.getSuccess();
    }
}
